//
//  FCArticleViewController.swift
//  miaoyin
//
//  Created by David on 2017/2/21.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

class FCArticleViewController: UIViewController, UIWebViewDelegate {

    var aid: String?
    
    
    convenience init(title: String, id: String){
        self.init()
        self.title = title
        aid = id
    }
    
    var webView: UIWebView!
    var progressBar: UIProgressView!
    //    var toolbar: UIToolbar!
    var backToolbar: UIToolbar!
    
    var bottomBar: UIVisualEffectView!
    
    var likeBtn: UIButton!
    var remarkBtn: UIButton!
    var shareBtn: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        
        webView = UIWebView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height))
        webView.delegate = self
        webView.scalesPageToFit = true
        webView.scrollView.contentInset.bottom += 44
        view.addSubview(webView)
        
        progressBar = UIProgressView(frame: CGRect(x: 0, y: 64, width: view.bounds.width, height: 0))
        view.addSubview(progressBar)
        progressBar.tintColor = themeColor1
        
        //        toolbar = UIToolbar(frame: CGRect(x: 0, y: view.frame.height - 44, width: view.frame.width, height: 44))
        //        view.addSubview(toolbar)
        //        var toolbarItems:[UIBarButtonItem] = []
        //        toolbarItems.append(UIBarButtonItem(barButtonSystemItem: .Undo, target: self, action: ""))
        //        toolbarItems.append(UIBarButtonItem(barButtonSystemItem: .Redo, target: self, action: ""))
        //        toolbarItems.append(UIBarButtonItem(barButtonSystemItem: .Refresh, target: self, action: ""))
        //
        //        toolbar.setItems(toolbarItems, animated: true)
        
        //        backToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 128, height: 44))
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "navbar_back"), style: .plain, target: self, action: #selector(FCArticleViewController.backBtnClicked))
        
        bottomBar = UIVisualEffectView(frame: CGRect(x: 0, y: view.frame.height-44, width: view.frame.width, height: 44))
        bottomBar.effect = UIBlurEffect(style: .extraLight)
        view.addSubview(bottomBar)
        
//        likeBtn = UIButton(frame: CGRect(x: 16, y: 12, width: 80, height: 20))
//        likeBtn.setImage(#imageLiteral(resourceName: "like"), for: .normal)
//        likeBtn.imageView?.contentMode = .scaleAspectFit
//        likeBtn.setTitle("0", for: .normal)
//        likeBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
//        likeBtn.setTitleColor(UIColor.gray, for: .normal)
//        bottomBar.addSubview(likeBtn)
        
        remarkBtn = UIButton(frame: CGRect(x: 8, y: 12, width: 88, height: 20))
        remarkBtn.setImage(#imageLiteral(resourceName: "remark"), for: .normal)
        remarkBtn.imageView?.contentMode = .scaleAspectFit
        remarkBtn.setTitle("0", for: .normal)
        remarkBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        remarkBtn.setTitleColor(UIColor.gray, for: .normal)
        bottomBar.addSubview(remarkBtn)
        
//        shareBtn = UIButton(frame: CGRect(x: view.frame.width - 44, y: 12, width: 24, height: 20))
//        shareBtn.setImage(#imageLiteral(resourceName: "share"), for: .normal)
//        shareBtn.imageView?.contentMode = .scaleAspectFit
//        bottomBar.addSubview(shareBtn)
        
        if aid != nil{
            let urlStr = "\(baseDomainName)/cms/index.php?c=detail&id=\(aid!)&type=m"
            
            print("aid:\(aid ?? "")")
            ChangyanSDK.getCommentCount(nil, topicSourceID: aid!, topicUrl: urlStr, complete: { (code, str) in
                if str != nil{
                    print(str!)
                    do{
                        let jsonObj = try JSONSerialization.jsonObject(with: str!.data(using: .utf8)!, options: .allowFragments) as? NSDictionary
                        let jsonRes = jsonObj?.object(forKey: "result") as? NSDictionary
                        let jsonData = jsonRes?.object(forKey: self.aid!) as? NSDictionary
                        let commentNum = jsonData?.object(forKey: "comments") as? Int
                        
                        if commentNum != nil{
                            if commentNum! < 1000 {
                                self.remarkBtn.setTitle("\(commentNum!)", for: .normal)
                            }else{
                                self.remarkBtn.setTitle("999+", for: .normal)
                            }
                        }
                        
                    }catch let err{
                        print(err)
                    }
                }
            })
            
            URLSession.shared.dataTask(with: URL(string: urlStr)!, completionHandler: { (data:Data?, resp:URLResponse?, err:Error?) in
                
                if err == nil{
                    if data != nil{
                        do{
                            let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                            let jsonData = jsonObj?.object(forKey: "data") as? NSDictionary
                            let news = jsonData?.object(forKey: "news") as? NSDictionary
                            let content = news?.object(forKey: "content") as? String
                            if content != nil{
                                DispatchQueue.main.async {
                                    self.webView.loadHTMLString(content!, baseURL: URL(string: baseDomainName)!)
                                }
                            }
                            
                        }catch let ex{
                            print(ex)
                        }
                    }
                }
            }).resume()
        }else{
            let urlStr = "\(baseDomainName)/cms/index.php?c=detail&id=&type=m"
            webView.loadRequest(URLRequest(url: URL(string: urlStr)!))
        }
        
        
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.interactivePopGestureRecognizer?.delegate = nil
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        progressBar.alpha = 1
        progressBar.setProgress(0.1, animated: true)
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        progressBar.setProgress(0.9, animated: true)
        UIView.animate(withDuration: 0.3) {
            self.progressBar.alpha = 0
        }
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        //        progressBar.progress = 1
        //        progressBar.alpha = 0
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func backBtnClicked(){
        
        if webView.canGoBack{
            webView.goBack()
            var backBtnItems:[UIBarButtonItem] = []
            backBtnItems.append(UIBarButtonItem(image: UIImage(named: "navbar_back"), style: .plain, target: self, action: #selector(FCArticleViewController.backBtnClicked)))
            backBtnItems.append(UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(WebArticleViewController.closeBtnClicked)))
            navigationItem.leftBarButtonItems = backBtnItems
        }else{
            _ = navigationController?.popViewController(animated: true)
        }
        
        
    }
    
    func closeBtnClicked(){
        _ = navigationController?.popViewController(animated: true)
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
